package com.example.a_java.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.a_java.common.Result;
import com.example.a_java.dto.LendingApprovalDTO;
import com.example.a_java.entity.LoanDisbursement;
import com.example.a_java.entity.LoanDisbursementApproval;
import com.example.a_java.service.LoanDisbursementApprovalService;
import com.example.a_java.service.LoanDisbursementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 放款审批接口控制器
 */
@RestController
@RequestMapping("/api/lending/approval")
public class LendingApprovalController {

    @Autowired
    private LoanDisbursementService loanDisbursementService;
    
    @Autowired
    private LoanDisbursementApprovalService loanDisbursementApprovalService;

    /**
     * 获取待审批放款列表
     */
    @GetMapping("/pending")
    public Result<IPage<LoanDisbursement>> getPendingApprovalList(
            @RequestParam(required = false) String contractNo,
            @RequestParam(required = false) String loanNo,
            @RequestParam(required = false) String customerName,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        IPage<LoanDisbursement> page = loanDisbursementService.getPendingApprovalList(
                contractNo, loanNo, customerName, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 审批放款申请
     */
    @PostMapping
    public Result<Object> approvalLending(@RequestBody LendingApprovalDTO approvalDTO) {
        // 假设当前用户ID、姓名和角色从上下文中获取
        Long userId = 1L; // TODO: 从上下文中获取当前用户ID
        String userName = "李财务"; // TODO: 从上下文中获取当前用户姓名
        String userRole = "财务经理"; // TODO: 从上下文中获取当前用户角色
        try {
            boolean result = loanDisbursementApprovalService.approve(
                    approvalDTO, userId, userName, userRole);
            if (result) {
                return Result.success("审批提交成功");
            } else {
                return Result.error("审批提交失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取审批历史
     */
    @GetMapping("/history/{disbursementId}")
    public Result<List<LoanDisbursementApproval>> getApprovalHistory(@PathVariable Long disbursementId) {
        List<LoanDisbursementApproval> history = loanDisbursementApprovalService.getApprovalHistory(disbursementId);
        return Result.success(history);
    }
} 
